const db = require("./database.js")

async function selectUserByUsername(username) {
  return new Promise((resolve, reject) => {
    db.all("select * from user where username = ?", [username], (err, rows) => {
      if (err) {
        reject(err);
      } else if (rows && rows.length > 0) {
        resolve(rows[0])
      } else {
        resolve(null)
      }
    });
  })
}

async function selectUserByToken(token) {
  return new Promise((resolve, reject) => {
    db.all("select * from user where token = ?", [token], (err, rows) => {
      if (err) {
        reject(err);
      } else if (rows && rows.length > 0) {
        resolve(rows[0])
      } else {
        resolve(null)
      }
    });
  })
}

async function selectUserByUserId(user_id) {
  return new Promise((resolve, reject) => {
    db.get("select * from user where user_id = ?", [user_id], (err, row) => {
      if (err) {
        reject(err);
      } else {
        resolve(row)
      }
    });
  })
}

async function insertUser(user) {
  return new Promise((resolve, reject) => {
    db.run("insert into user (username, password) values (?,?)", [user.username, user.password], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    });
  })
}

async function updateUserToken(user) {
  return new Promise((resolve, reject) => {
    db.run("update user set token = ? where user_id = ?", [user.token, user.user_id], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    });
  })
}

async function updateUserNickname(user) {
  return new Promise((resolve, reject) => {
    db.run("update user set nickname = ? where user_id = ?", [user.nickname, user.user_id], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    });
  })
}

module.exports = {
  selectUserByToken, 
  selectUserByUsername,
  selectUserByUserId,
  insertUser,
  updateUserToken,
  updateUserNickname
}
